package com.suineg.pms.commons.wabacus;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.suineg.pms.commons.AppConfig;
import com.suineg.pms.commons.UserHoder;
import com.suineg.pms.entity.User;
import com.suineg.pms.entity.base.Building;
import com.suineg.pms.entity.base.Community;
import com.suineg.pms.entity.base.Room;
import com.suineg.pms.entity.commons.SystemInfo;
import com.suineg.pms.service.base.BuildingService;
import com.suineg.pms.service.base.CommunityService;
import com.suineg.pms.service.base.RoomService;
import com.suineg.pms.util.StringUtils;
import com.wabacus.config.component.application.report.ReportBean;
import com.wabacus.system.ReportRequest;
import com.wabacus.system.component.application.report.configbean.editablereport.AbsEditableReportEditDataBean;
import com.wabacus.system.intercept.AbsInterceptorDefaultAdapter;
import com.wabacus.util.Consts;

/**
 * 批量生成楼栋 的拦截器（按单元数）
 * <pre>
 * 	在保存时，根据页面输入的信息进行批量生成房屋
 * </pre>
 *@author Suine
 */
public class BuildingMultCreateForUnitCountIntercepter extends AbsInterceptorDefaultAdapter {
	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	private BuildingService buildingService = AppConfig.getInstance().getWac().getBean(BuildingService.class);
	private CommunityService communityService = AppConfig.getInstance().getWac().getBean(CommunityService.class);
	private RoomService roomService = AppConfig.getInstance().getWac().getBean(RoomService.class);

	private Integer unitCount;
	private Integer floorCount;
	private Integer roomCount;
	private Long buildingId;
	
	private Building building = null;
	private Long elevater = null;
	private Long buildType = null;

	@Override
	public int doSave(ReportRequest rrequest, ReportBean rbean, AbsEditableReportEditDataBean editbean) {
		// TODO Auto-generated method stub
		List<Map<String,String>> list = rrequest.getLstInsertedData(rbean);
		Map<String,String> mRowData = list.get(0);
		
		try {
			unitCount = Integer.valueOf(mRowData.get("unit_count"));
			floorCount = Integer.valueOf(mRowData.get("floor_count"));
			roomCount = Integer.valueOf(mRowData.get("room_count"));
			buildingId = Long.valueOf(mRowData.get("building_id"));
			elevater = Long.valueOf(mRowData.get("elevater"));
			buildType = Long.valueOf(mRowData.get("typ"));
			
			building = buildingService.get(buildingId);
			
			String buildingNo = building.getNo();
			String unitMaxNo = roomService.findMaxUniNoByBuidlingId(buildingId);
			if(!StringUtils.isEmpty(unitMaxNo) && !StringUtils.isNumber(unitMaxNo)){
				rrequest.getWResponse().getMessageCollector().warn("要批量生成的楼栋下面的单元号必需是数字!", false, Consts.STATECODE_FAILED);
				return WX_RETURNVAL_SUCCESS;
			}
			
			
			if(StringUtils.isEmpty(unitMaxNo)){
				unitMaxNo = "0";
			}
			
			User user = new User(UserHoder.getCurrentShiroUser().getId());
			Date now = new Date();
			SystemInfo elevaterInfo = new SystemInfo(elevater);
			SystemInfo buildTypeInfo = new SystemInfo(buildType);
			
			Room room = null;
			List<Room> rooms = Lists.newArrayList();
			
			//因为，按单元数批量生成。是从数据库中最大单元号+1 开始的所以。不存在重复问题.
			for(int u = 1; u <= unitCount; u++){		//单元
				String newUnitNo = StringUtils.ldap(Long.valueOf((Integer.valueOf(unitMaxNo) + u) + ""), 3, '0');
				for(int f = 1;f <= floorCount; f++){	//楼层
					String fNo = StringUtils.ldap(Long.valueOf(f+""), 2, '0');
					for(int r = 1; r <= roomCount; r++){//室号
						String rNo = StringUtils.ldap(Long.valueOf(r + ""), 2, '0');
						String roomNo = fNo + rNo;
						String houseNo = buildingNo + newUnitNo + roomNo; 
						room = new Room(houseNo,houseNo,building.getCommunity(),building,Integer.valueOf(newUnitNo).toString(),roomNo,null,user,elevaterInfo,now,buildTypeInfo);
						rooms.add(room);
					}
				}
			}
			
			//判断是否重复
			String houseNos = StringUtils.listPaseToString(rooms, "houseNo");
			List<Room> roomList = roomService.findRoomByHouseNo(houseNos);
			if(roomList != null && !roomList.isEmpty()){
				//去年重复
				rooms.removeAll(roomList);
				rrequest.getWResponse().getMessageCollector().alert("批量生成时，发现已存在房屋，系统以跳过重复的房屋", true);
			}
			
			//保存
			roomService.saveAll(rooms);
		} catch (Exception e) {
			rrequest.getWResponse().getMessageCollector().warn("保存失败!请与管理联系", false, Consts.STATECODE_FAILED);
			e.printStackTrace();
		}
		return WX_RETURNVAL_SUCCESS;
	}

	/**
	 * 检查表单合法性
	 * @return
	 */
	public boolean checkForm(ReportRequest rrequest, Map<String, String> mRowData){
		boolean f = true;
		
		String no = mRowData.get("no");
		String communityId = mRowData.get("community_id");
		String name = mRowData.get("name");
		String id = mRowData.get("id");
		
		List<Building> list = null;
		Building buidling = null;
		Community community = null;
		
		if(StringUtils.isEmpty(id)){		//新加
			buidling = buildingService.findByNo(no);
			if(buidling != null){
				f = false;
				rrequest.getWResponse().getMessageCollector().warn("此楼栋编号已存在!", false, Consts.STATECODE_FAILED);
			}
			community = communityService.get(Long.valueOf(communityId));
			list = community.getBuildingList();
			for(Building b : list){
				if(b.getName().equals(name)){
					f = false;
					rrequest.getWResponse().getMessageCollector().warn("此楼栋名已存在!", false, Consts.STATECODE_FAILED);
					break;
				}
				
			}
		}			//暂取消修改功能
		
		return f;
	}

}

